package com.dsl.dslsuzhou.controller;

import com.dsl.dslsuzhou.model.dto.DeviceImportDto;
import com.dsl.dslsuzhou.service.DeviceImportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 设备导入控制器
 */
@RestController
@RequestMapping("/api/${api-module}/device")
@Slf4j
public class DeviceImportController {
    
    @Autowired
    private DeviceImportService deviceImportService;
    
    /**
     * Excel文件上传并导入设备数据
     */
    @PostMapping("/import")
    public ResponseEntity<Map<String, Object>> importDevicesFromExcel(@RequestParam("file") MultipartFile file) {
        try {
            // 验证文件
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse(400, "文件不能为空"));
            }
            
            if (!isExcelFile(file)) {
                return ResponseEntity.badRequest().body(createErrorResponse(400, "请上传Excel文件(.xlsx或.xls)"));
            }
            
            // 解析Excel文件
            List<DeviceImportDto> devices = parseExcelFile(file);
            
            if (devices.isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse(400, "Excel文件中没有有效数据"));
            }
            
            // 批量导入设备
            Map<String, Object> result = deviceImportService.importDevices(devices);
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            return ResponseEntity.status(500).body(createErrorResponse(500, "导入失败: " + e.getMessage()));
        }
    }
    
    /**
     * 批量导入设备数据（JSON格式）
     */
    @PostMapping("/import/json")
    public ResponseEntity<Map<String, Object>> importDevicesFromJson(@RequestBody List<DeviceImportDto> devices) {
        try {
            if (devices == null || devices.isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse(400, "设备数据不能为空"));
            }
            
            Map<String, Object> result = deviceImportService.importDevices(devices);
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            return ResponseEntity.status(500).body(createErrorResponse(500, "导入失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取Excel模板
     */
    @GetMapping("/template")
    public ResponseEntity<Map<String, Object>> getImportTemplate() {
        Map<String, Object> template = new HashMap<>();
        template.put("code", 200);
        template.put("message", "Excel导入模板");
        
        List<Map<String, Object>> columns = new ArrayList<>();
        columns.add(createColumn("设备类Key", "deviceTypeKey", "string", true, "如: AC001, LIGHT001"));
        columns.add(createColumn("设备类名称", "deviceTypeName", "string", false, "如: 中央空调, LED照明"));
        columns.add(createColumn("设备ID", "deviceId", "string", true, "设备唯一标识"));
        columns.add(createColumn("设备名称", "deviceName", "string", true, "如: 空调A01"));
        columns.add(createColumn("设备密钥", "deviceSecret", "string", false, "设备认证密钥"));
        columns.add(createColumn("设备分组", "deviceGroupName", "string", false, "如: 冷水机组A"));
        columns.add(createColumn("设备分组ID", "deviceGroupId", "string", false, "分组唯一标识"));
        columns.add(createColumn("设备型号", "deviceModel", "string", false, "如: GREE-5P"));
        
        template.put("columns", columns);
        return ResponseEntity.ok(template);
    }
    
    /**
     * 解析Excel文件
     */
    private List<DeviceImportDto> parseExcelFile(MultipartFile file) throws IOException {
        List<DeviceImportDto> devices = new ArrayList<>();
        
        try (Workbook workbook = new XSSFWorkbook(file.getInputStream())) {
            Sheet sheet = workbook.getSheetAt(0);
            
            // 跳过标题行，从第二行开始读取数据
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;
                
                DeviceImportDto device = new DeviceImportDto();
                
                // 按列读取数据 (假设Excel列顺序: 设备类Key, 设备类名称, 设备ID, 设备名称, 设备密钥, 设备分组, 设备分组ID, 设备型号)

                device.setDeviceTypeKey(getCellStringValue(row.getCell(0)));
                device.setDeviceTypeName(getCellStringValue(row.getCell(1)));
                device.setDeviceId(getCellStringValue(row.getCell(2)));
                device.setDeviceName(getCellStringValue(row.getCell(3)));
                device.setDeviceSecret(getCellStringValue(row.getCell(4)));
                device.setDeviceGroupName(getCellStringValue(row.getCell(5)));
                device.setDeviceGroupId(getCellStringValue(row.getCell(6)));
                device.setDeviceModel(getCellStringValue(row.getCell(7)));
                
                // 只添加有效的设备数据
                if (device.getDeviceId() != null && !device.getDeviceId().trim().isEmpty() &&
                    device.getDeviceName() != null && !device.getDeviceName().trim().isEmpty()) {
                    log.info("添加有效数据：{}", device.toString());
                    devices.add(device);
                }
            }
        }
        
        return devices;
    }
    
    /**
     * 获取单元格字符串值
     */
    private String getCellStringValue(Cell cell) {
        if (cell == null) return null;
        
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue().trim();
            case NUMERIC:
                return String.valueOf((long) cell.getNumericCellValue());
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            default:
                return null;
        }
    }
    

    
    /**
     * 检查是否为Excel文件
     */
    private boolean isExcelFile(MultipartFile file) {
        String filename = file.getOriginalFilename();
        return filename != null && (filename.endsWith(".xlsx") || filename.endsWith(".xls"));
    }
    
    /**
     * 创建错误响应
     */
    private Map<String, Object> createErrorResponse(int code, String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("code", code);
        response.put("message", message);
        return response;
    }
    
    /**
     * 创建列定义
     */
    private Map<String, Object> createColumn(String title, String field, String type, boolean required, String example) {
        Map<String, Object> column = new HashMap<>();
        column.put("title", title);
        column.put("field", field);
        column.put("type", type);
        column.put("required", required);
        column.put("example", example);
        return column;
    }
}
